<?php
###
#  Baing PHP 框架 1.0.0
#  http://baing.co/
#
#  Copyright: 白晓阳
#  License: CC BY-NC-SA 4.0
#  https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh
###

namespace bai;

use bai\feature\BaingException;
use bai\resource\application\Logger;


abstract class Resource extends Baing
{
    private static array $entry = [];

    public static function setup(array $runtime = []): ?static
    {
        $id = static::setupId($runtime);
        if (isset(self::$entry[$id])) {
            return self::$entry[$id] ?: null;
        }

        Logger::print("++ Resource setup: $id", Logger::INFO);
        try {
            self::$entry[$id] = static::setupEntry($runtime);
        } catch (BaingException $e) {
            Logger::print("++ Resource fail: $id", Logger::WARING);
            self::$entry[$id] = false;
            throw $e;
        }
        return self::$entry[$id] ?: null;
    }

    protected static function setupId(array &$runtime, string $key = ''): string
    {
        $id = static::class;
        if ($key) {
            $id .= ":$key";
        }
        return $runtime['id'] = $id;
    }
    
    protected static function setupEntry(array &$runtime): ?self
    {
        return new static($runtime);
    }

    public function __destruct()
    {
        $this->close();
    }

    protected function close()
    {
        unset(self::$entry[$this->find('id')]);
    }
}
